package com.glls.sbdemo22.interceptor;

import com.glls.sbdemo22.anno.UnInterception;
import com.glls.sbdemo22.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @date 2023/5/16
 * @desc
 */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println("拦截器:当前请求路径"+uri);

        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //得到 请求方法对象
            Method method = handlerMethod.getMethod();
            String methodName = method.getName();
            log.info("====拦截到了方法：{}，在该方法执行之前执行====", methodName);

            // 通过方法，可以获取该方法上的自定义注解，然后通过注解来判断该方法是否要被拦截
            // @UnInterception 是我们自定义的注解
            UnInterception unInterception = method.getAnnotation(UnInterception.class);
            if (null != unInterception) {

                // 接口中  标注了这个注解的方法 直接放行
                return true;
            }

        }

        // 对于 其他的 （就是没有放行注解的方法） 需要判断请求头有没有带token
        String token = request.getHeader("token");
        System.out.println("token:-----"+token);
        if(token==null){
            R r = R.error().message("用户未认证");
            print(response,r);
            return false;
        }else{
            return true;
        }


    }

    //封装一个 向前端响应数据的方法
    public void print(HttpServletResponse response, R r) {

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        writer.println(r);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("后置拦截");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("最终拦截");
    }
}
